package org.javaboy.vhr.config;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 做出最终的访问控制（授权）决定
 */
@Component
public class CustomUrlDecisionManager implements AccessDecisionManager {

    /**
     * 为传递的参数解决访问控制决策。
     * @param authentication 调用方法（不为null）
     * @param object 被调用的受保护对象
     * @param configAttributes 与要调用的受保护对象关联的配置属性
     * @throws AccessDeniedException 如果访问被拒绝，因为身份验证不拥有所需的权限或ACL特权
     * @throws InsufficientAuthenticationException 如果由于身份验证未提供足够的信任级别而拒绝访问
     */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        for (ConfigAttribute configAttribute : configAttributes) {
            String needRole = configAttribute.getAttribute();
            if ("ROLE_LOGIN".equals(needRole)) {
                if (authentication instanceof AnonymousAuthenticationToken) {
                    throw new AccessDeniedException("尚未登录，请登录!");
                }else {
                    return;//放行
                }
            }
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();//授予的权限，如果令牌尚未通过身份验证，则为空集合。 永远不会为空。
            for (GrantedAuthority authority : authorities) {
                if (authority.getAuthority().equals(needRole)) {
                    return;//放行
                }
            }
        }
        throw new AccessDeniedException("权限不足，请联系管理员!");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
